import datetime as dt
from ycdata.models import Market_data_cur_date,StockProfile,StockBlacklist,Market_data_update_stat
from ycdata.models import Block_profile,Block_profile_main
from ycdata.update_data_sub import getTradeDateInterval
from ycdata.update_data import init_market_data,update_market_data,update_block_file

def getMarketUpdateContext():
    marketStat = {}
    date_now = dt.date.today()
    date_now_str = date_now.strftime('%Y-%m-%d')
    marketDateObj = Market_data_cur_date.objects.all()
    #如果市场数据还未初始化，则进行第一次初始化，并自动更新数据
    if not marketDateObj:
        init_market_data()
        update_market_data()
    marketDateObj = Market_data_cur_date.objects.all()
    last_date = marketDateObj.values('market_cur_date').first()['market_cur_date']
    lastlast_date = marketDateObj.values('market_last_date').first()['market_last_date']
    last_date_str = last_date.strftime('%Y-%m-%d')
    lastlast_date_str = lastlast_date.strftime('%Y-%m-%d')
    last_date_str2 = last_date.strftime('%Y%m%d')
    date_now_str2 = date_now.strftime('%Y%m%d')
    days = getTradeDateInterval(last_date_str2,date_now_str2)
    marketStat.update({'now_date':date_now_str,'last_date': last_date_str,'update_daynum':days - 1})
    marketStat.update({'start_date':lastlast_date_str,'end_date': last_date_str})
    stocknumDict = {}
    cyNum = 0
    kcNum = 0
    shNum = 0
    szNum = 0
    normalNum = 0
    stockProfileObj = StockProfile.objects.all().values('code','list_date')
    for stock in stockProfileObj:
        normalNum += 1
        stockcode = stock['code']
        if stockcode[:2] == '30':
            cyNum += 1
        if stockcode[:2] == '68':
            kcNum += 1
        if '.SZ' in stockcode:
            szNum += 1
        if '.SH' in stockcode:
            shNum += 1
    blackstocknum = StockBlacklist.objects.all().count()
    stocknumDict.update({'normal': normalNum,'sh':shNum,'sz':szNum,'cy':cyNum,'kc':kcNum,'all':normalNum + blackstocknum})
    marketStat.update({'table_stocknum':stocknumDict})

    lastMarketStatObj = Market_data_update_stat.objects.all().filter(trade_date_end = last_date)
    new_stocklistObj = lastMarketStatObj.filter(event_type = 'new_stock')
    new_stocklist = []
    if new_stocklistObj:
        new_stock_list = new_stocklistObj.values('code','name')
        for stock in new_stock_list:
            stock_code = stock['code']
            stock_name = stock['name']
            list_date = [ele['list_date'] for ele in stockProfileObj if ele['code'] == stock_code][0] 
            list_date_str = list_date.strftime('%Y-%m-%d')
            new_stocklist.append({'code':stock_code, 'name':stock_name,'list_date':list_date_str})
        marketStat.update({'new_stocklist':new_stocklist})
    
    next_stocklistObj = lastMarketStatObj.filter(event_type = 'next_stock')
    next_stocklist = []
    if next_stocklistObj:
        next_stock_list = next_stocklistObj.values('code','name')
        for stock in next_stock_list:
            stock_code = stock['code']
            stock_name = stock['name']
            list_date_str  = '下一交易日'
            next_stocklist.append({'code':stock_code, 'name':stock_name,'list_date':list_date_str})
    marketStat.update({'next_stocklist':next_stocklist})
    dest_stocklistObj = lastMarketStatObj.filter(event_type = 'de_st')
    dest_stocklist = []
    if dest_stocklistObj:
        dest_stock_list = dest_stocklistObj.values('code','name')
        for stock in dest_stock_list:
            stock_code = stock['code']
            stock_name = stock['name']
            list_date = [ele['list_date'] for ele in stockProfileObj if ele['code'] == stock_code][0] 
            dest_stocklist.append({'code':stock_code, 'name':stock_name,'list_date':list_date_str})
    marketStat.update({'dest_stocklist':dest_stocklist})
    del_stocklistObj = lastMarketStatObj.filter(event_type__in = ['isST','isTui'])
    del_stocklist = []
    if del_stocklistObj:
        del_stock_list = del_stocklistObj.values('code','name','event_type')
        for stock in del_stock_list:
            stock_code = stock['code']
            stock_name = stock['name']
            event_type = stock['event_type']
            if event_type == 'isST':
                type_str = '被ST'
            elif event_type == 'isTui':
                type_str = '退市'
            del_stocklist.append({'code':stock_code,'name':stock_name,'type':type_str})
        marketStat.update({'del_stocklist':del_stocklist})
    
    return marketStat

def getBlockFileUpdateContext():
    date_now = dt.date.today()
    date_now_str = date_now.strftime('%Y-%m-%d')
    blockStat = {}
    block_itemnum = {}
    gn_blocklist = []
    hy_blocklist = []
    zs_blocklist = []
    fg_blocklist = []
    marketDateObj = Market_data_cur_date.objects
    if marketDateObj:
        last_date = marketDateObj.values('block_file_cur_date').first()['block_file_cur_date']
        last_date_str = last_date.strftime('%Y-%m-%d')
    blockStat.update({'now_date':date_now_str,'last_date':last_date_str})

    blockProfileObj = Block_profile_main.objects#包括了行业和概念两个板块，只有板块信息，没有板块与个股对应关系
    gn_blocklist = list(blockProfileObj.filter(block_type = 'gn').values('block_code','block_name','total_num'))
    # gnBlockCodeList = list(set(gnBlockCodeList))
    block_itemnum.update({'gn':gn_blocklist.__len__()})
     

    hy_blocklist = list(blockProfileObj.filter(block_type__in = ['hy1','hy2']).values('block_code','block_name','total_num'))
    # hyBlockCodeList = list(set(hyBlockCodeList))
    block_itemnum.update({'hy':hy_blocklist.__len__()})

    blockProfileObj = Block_profile.objects#包括了风格、指数、行业和概念等4板块，包括了板块信息、板块与个股对应关系
    fgBlockCodeList = list(blockProfileObj.filter(block_type = 'fg').values_list('block_code',flat=True))
    fgBlockCodeList = list(set(fgBlockCodeList))
    for fgBlockCode in fgBlockCodeList:
        ele = blockProfileObj.filter(block_code = fgBlockCode).values('block_code','block_name','total_num').first()
        fg_blocklist.append(ele)
    # fg_blocklist = blockProfileObj.filter(block_code__in = fgBlockCodeList)
    block_itemnum.update({'fg':fgBlockCodeList.__len__()})

    zsBlockCodeList = list(blockProfileObj.filter(block_type = 'zs').values_list('block_code',flat=True))
    zsBlockCodeList = list(set(zsBlockCodeList))
    for zsBlockCode in zsBlockCodeList:
        ele = blockProfileObj.filter(block_code = zsBlockCode).values('block_code','block_name','total_num').first()
        zs_blocklist.append(ele)
    block_itemnum.update({'zs':zsBlockCodeList.__len__()})


    blockStat.update({'block_itemnum':block_itemnum})
    blockStat.update({'gn_blocklist':gn_blocklist})
    blockStat.update({'hy_blocklist':hy_blocklist})
    blockStat.update({'zs_blocklist':zs_blocklist})
    blockStat.update({'fg_blocklist':fg_blocklist})

    return blockStat

# def getTradeDays(start_date,end_date):
#     days = 0
#     if end_date < start_date:
#         return 0
#     tradedateList = list(MarketTradeDate.objects.all().values_list('trade_date',flat=True))
#     print('tradedate list = ',tradedateList)
#     while end_date >= start_date:
#         if end_date in tradedateList:
#             days += 1
#         end_date = end_date - dt.timedelta(days=1)
#     return days


def getMarketOverviewContext():
    marketStat = {}


    return marketStat